//
//  String+HKExtension.swift
//  App架构Swift
//
//  Created by 胡锦涛 on 2019/2/19.
//  Copyright © 2019 胡锦涛. All rights reserved.
//

import UIKit

extension String {
    
    /// 获取字符串长度
    var hk_length: Int {
        return self.count
    }
    
    ///过滤空格
    public var hk_noSpaceString: String{
        let s = self as NSString
        return s.replacingOccurrences(of:" ", with: "") as String
    }
    
    ///手机号加密显示
    public func hk_safeMdn() -> String{
        var resultMdn:String = ""
        if !self.isEmpty {
            let phoneStr:NSMutableString = NSMutableString(string: self)
            let tempRange:NSRange = NSMakeRange(3, 4)
            phoneStr.replaceCharacters(in: tempRange, with: "****")
            resultMdn = "\(phoneStr)"
        }else {
            resultMdn = ""
        }
        return resultMdn
    }
    
    ///获取字符串不为空的值
    public func hk_value() -> String {
        if self.isEmpty {
            return ""
        }else {
            return self
        }
    }
    
    //是否是手机号
    var hk_IsMobile: Bool {
        let mobile = "^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$"
        let predicate = NSPredicate.init(format: "SELF MATCHES %@", mobile)
        return predicate.evaluate(with: self)
    }
    
    ///是否包含中文
    public func hk_isIncludeChinese() -> Bool {
        for (_, value) in self.enumerated() {
            if ("\u{4E00}" <= value  && value <= "\u{9FA5}") {
                return true
            }
        }
        return false
    }
    
    ///字符串包含
    public func hk_contains(substr: String) -> Bool {
        return self.range(of: substr) != nil
    }
    
    ///字符串截取
    public func hk_componentsSeparated(_ componentsSeparat:String) -> [String:Any]{
        
        let a = components(separatedBy: componentsSeparat)
        var dict = [String:Any]()
        for s in a {
            
            let str = s.hk_urlDecoded() as NSString
            
            if str.contains("="){
                let range = str.range(of: "=")
                let key = str.substring(to: range.location)
                let value = str.substring(from: range.location+1)
                dict[key] = value
            }
        }
        return dict
    }
    
    /// 获取富文本字符串
    func hk_attributeString(color: UIColor, font: UIFont) -> NSAttributedString {
        let attributesDic = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font: font]
        return NSAttributedString.init(string: self, attributes: attributesDic)
    }
    
    ///文本添加行间距
    public func hk_add(lineSpacing:CGFloat, withFontSize fontSize:CGFloat) -> NSAttributedString{
        let paraph = NSMutableParagraphStyle()
        paraph.lineSpacing = lineSpacing
        let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize),
                          NSAttributedString.Key.paragraphStyle : paraph]
        
        return NSAttributedString(string: self, attributes: attributes)
    }
    
    /// 计算文本高度
    func hk_textHeight(font: UIFont, maxWidth: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat {
        let lable = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: maxWidth, height: 0))
        lable.font = font
        lable.text = self
        lable.numberOfLines = 0
        return lable.sizeThatFits(CGSize.init(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)).height
    }
    
    /// 计算文本宽度
    func hk_textWidth(font: UIFont) -> CGFloat {
        let lable = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: CGFloat.greatestFiniteMagnitude, height: 0))
        lable.font = font
        lable.text = self
        lable.numberOfLines = 0
        return lable.sizeThatFits(CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).width
    }
    
    ///字符串转字典
    public var hk_jsonDictionary: Any?{
        
        let jsonData:Data = self.data(using: .utf8)!
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict
        }
        HKLog("字符串josn解析失败")
        return nil
    }
    
    /// 判断为整数
    func hk_isPureInt() -> Bool{
        let scan: Scanner = Scanner(string: self)
        
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd
        
    }
}
///URL Enode
extension String {
    
    ///将原始的url编码为合法的url
    func hk_urlEncoded() -> String {
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
            .urlQueryAllowed)
        return encodeUrlString ?? ""
    }
    
    ///将编码后的url转换回原始的url
    func hk_urlDecoded() -> String {
        return self.removingPercentEncoding ?? ""
    }
}
extension String {
    /// 将十六进制颜色转伟UIColor
    /// - Returns: UIColor
    public func hk_toUIColor() -> UIColor {
        //处理数值
        var cString = self.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        let length = (cString as NSString).length
        //错误处理
        if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
            return UIColor.white
        }
        
        if cString.hasPrefix("#"){
            cString = (cString as NSString).substring(from: 1)
        }
        
        //字符chuan截取
        var range = NSRange()
        range.location = 0
        range.length = 2
        
        let rString = (cString as NSString).substring(with: range)
        
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        
        range.location = 4
        let bString = (cString as NSString).substring(with: range)
        
        //存储转换后的数值
        var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
        //进行转换
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        //根据颜色值创建UIColor
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
    }
}
//MARK: 其他处理
extension String {
    subscript (str:String) -> String? {
        get {
            guard contains(str) else{
                return nil
            }
            let nsstr = self as NSString
            let range = nsstr.range(of: str)
            return nsstr.substring(to: range.location + 1)
        }
    }
}

extension String{
    ///过滤空格
    func hk_trimmedString() -> String {
        return self.trimmingCharacters(in: .whitespaces)
    }
    
}

extension String {
    ///Emoji个数
    var hk_countWithEmoji: Int {
        var count = 0
        for substring in self {
            if substring.hk_isEmoji {
                count += 2
            } else {
                count += 1
            }
        }
        return count
    }
}

extension String {
    ///是否包含Emoji
    var hk_containsEmoji: Bool {
        var count = 0
        for substring in self {
            if substring.hk_isEmoji {
                count += 1
                
            }
        }
        return count > 0 ? true : false
    }
}

extension Character {
    var hk_isEmoji: Bool {
        for scalar in unicodeScalars {
            if scalar.hk_isEmoji {
                return true
            }
        }
        return false
    }
}

extension UnicodeScalar {
    var hk_isEmoji: Bool {
        switch value {
        case 0x1F600...0x1F64F, // Emoticons
        0x1F300...0x1F5FF, // Misc Symbols and Pictographs
        0x1F680...0x1F6FF, // Transport and Map
        0x1F1E6...0x1F1FF, // Regional country flags
        0x2600...0x26FF,   // Misc symbols
        0x2700...0x27BF,   // Dingbats
        0xFE00...0xFE0F,   // Variation Selectors
        0x1F900...0x1F9FF,  // Supplemental Symbols and Pictographs
        127000...127600, // Various asian characters
        65024...65039, // Variation selector
        9100...9300, // Misc items
        8400...8447: // Combining Diacritical Marks for Symbols
            return true
        default:
            return false
        }
    }
}
